<?php
/**
 * 用户令牌数据模型
 */
class M_Token extends Model {

    public function __construct() {
        $this->table = TB_PREFIX.'token';
        parent::__construct();
    }

    /**
     * 新增token信息到token表
     */
    function insertToken($token = '', $user_id = ''){
        //不被清除掉的token对应id
        $s_commonTkId = 154;
        $a_commonTkId = 178;
        //如果任意一个参数无效即无效
        if(!$token || ! $user_id){
            return false;
        }
        $time = CUR_TIMESTAMP;
        // 1.新增token
        $insert_data['token'] = $token;
        $insert_data['user_id'] = $user_id;
        $insert_data['ctime'] = $time;
        $insert_data['mtime'] = $time;
        
        $tk_id = $this->Insert($insert_data);
        // 2.将原有用户id对应的token置为无效
        if($tk_id){
            if($user_id == 24){//如果用户是24号的话不清除万能token
                $this->Where(' user_id = '.$user_id.' and tk_id <> '.$tk_id.' and tk_id <> '.$s_commonTkId)->UpdateOne(['is_valid' => 0, 'mtime' => $time]);
            }
            elseif($user_id == 88){//如果用户是88号的话不清除万能token
                $this->Where(' user_id = '.$user_id.' and tk_id <> '.$tk_id.' and tk_id <> '.$a_commonTkId)->UpdateOne(['is_valid' => 0, 'mtime' => $time]);
            }
            else{
                $this->Where(' user_id = '.$user_id.' and tk_id <> '.$tk_id)->UpdateOne(['is_valid' => 0, 'mtime' => $time]);
            }
        }

        return true;
    }

    /**
     * 更新token信息
     */
    function updateToken($token = ''){
        if(!$token){
            return false;
        }

        $this->Where(['token' => $token, 'is_valid' => 1])->UpdateOne(['mtime' => CUR_TIMESTAMP]);
        return true;
    }

    /**
     * 检测token是否有效
     */
    function checkToken($token = ''){
        if(!$token){
            return false;
        }

        $cnt = $this->Where(['is_valid' => 1, 'token' => $token])->Total();

        if($cnt > 0){//如果有说明存在，此处进行时效性判断
            $time = CUR_TIMESTAMP;

            $res = $this->Where(['is_valid' => 1, 'token' => $token])->SelectOne();
            
            $mtime = 0;
            if(!empty($res) && is_array($res)){
                $mtime = $res['mtime'];
            }
            
            //生存时间为30分钟 30 * 60 = 1800
            $liveTime = $mtime + 1800;
            if($liveTime < $time){//最大生存时间小余当前时间 用户长久不动  失效了
                return false;
            }

            return true;
        }

        return false;
    }
    
}




